<template>
  <div>
    <el-form :ref="loginFormRef" :model="loginForm" :rules="loginRules" size="medium" label-width="0">
      <el-form-item prop="username">
        <el-input v-model="loginForm.username" placeholder="Username"></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input v-model="loginForm.password" type="password" placeholder="Password"
                  autocomplete="off" @keyup.enter.native="submitForm"></el-input>
      </el-form-item>
      <el-button :loading="loading" type="primary" class="width-100" @click="submitForm">登录</el-button>
    </el-form>
  </div>
</template>

<script>
  import {setStorage, StorageKey} from "@/config/sessions";
  import {momentFormat} from "@/config/common";

  export default {
    name: "LoginForm",
    data() {
      return {
        loading: false,
        loginFormRef: 'loginFormRef',
        loginForm: {
          username: '',
          password: ''
        },
        loginRules: {
          username: [
            {required: true, message: '请输入用户名', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
        },
      };
    },
    methods: {
      submitForm() {
        if (this.loading) return;
        this.$refs[this.loginFormRef].validate((valid) => {
          if (valid) {
            this.loading = true;
            API.user.login(this.loginForm).then(result => {
              this.loading = false;
              const {userId, token, user = {}, expiresIn, refreshToken} = result;
              const {username = '', name = '', nickname = '', tel = '', email = '', role = '',isAdmin=''} = user;
              setStorage(StorageKey.tokenLimit, expiresIn * 60);
              setStorage(StorageKey.refreshToken, refreshToken);
              setStorage(StorageKey.tokenTime, moment().format(momentFormat.timestamp));
              setStorage(StorageKey.userId, userId);
              setStorage(StorageKey.username, username);
              setStorage(StorageKey.token, token);
              setStorage(StorageKey.name, name);
              setStorage(StorageKey.nickname, nickname);
              setStorage(StorageKey.tel, tel);
              setStorage(StorageKey.email, email);
              setStorage(StorageKey.role, role);
              setStorage(StorageKey.isAdmin, isAdmin);

              this.$emit('success');
            }).catch(err => {
              this.loading = false;
            });
          }
        });
      },
    },
  }
</script>

<style scoped>

</style>
